package com.syyo.admin.config.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.syyo.admin.common.enums.ResultEnum;
import com.syyo.admin.common.exception.SysException;
import com.syyo.admin.config.security.domain.JwtUser;
import com.syyo.admin.domain.entity.SysUser;
import com.syyo.admin.mapper.SysUserMapper;
import com.syyo.admin.service.SysRoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * security的service，实现loadUserByUsername方法
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleService roleService;

    /**
     * 只要这里发生异常，就会被security捕捉到
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        SysUser user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new SysException(ResultEnum.E_80006.getCode(), ResultEnum.E_80006.getMessage());
        } else {
            //用户禁用
            if (0 == user.getStatus()) {
                throw new SysException(ResultEnum.E_80007.getCode(), ResultEnum.E_80007.getMessage());
            }
        }
        // 获取用户的权限
        Collection<GrantedAuthority> authorities = roleService.findByUsersId(user.getUserId());

        return createJwtUser(user,authorities);
    }

    /**
     * 创建jwtUser对象，封装
     *
     * @param user
     * @return
     */
    private UserDetails createJwtUser(SysUser user,Collection<GrantedAuthority> authorities) {
        return new JwtUser(
                user.getDatasourceName(),
                user.getUserId(),
                user.getUserName(),
                user.getPassWord(),
                user.getNickName(),
                user.getDeptId(),
                user.getPhone(),
                user.getEmail(),
                user.getSex(),
                user.getAvatar(),
                true,
                authorities);
    }

}
